#! /usr/bin/env python
# -*- coding: utf8 -*-

import pygtk
pygtk.require('2.0')

import gtk
import sys

if sys.version_info[:2] == (2, 5):
    from xml.etree import ElementTree as et
else:
    from elementtree import ElementTree as et

class distribution(object):
    def __init__(self, node):
        self.__node = node

        self.__name        = node.find("name").text
        self.__pretty_name = node.find("pretty_name").text

        self.__description = node.find("description")
        self.__desc_label  = None

        if self.__description != None:
            self.__description = self.__description.text
            self.__desc_label = gtk.Label(self.__description)
            self.__desc_label.show_all()

        self.__parameters = {}
        self.__containers = []
        [self.__conf_param(x) for x in node.findall("./parameters/param")]
        [x.show_all() for x in self.__containers]

    def __conf_param(self, node):
        name = node.text

        container = gtk.HBox()
        container.pack_start(gtk.Label(name + ":"), padding=5)

        self.__parameters[name] = gtk.Entry()
        container.pack_start(self.__parameters[name], padding=5)
        self.__containers.append(container)

    def append_elements(self, parent):
        if self.__desc_label != None:
            parent.pack_start(self.__desc_label, padding=5)
            parent.reorder_child(self.__desc_label, len(parent) - 2)

        for i in self.__containers:
            parent.pack_start(i, padding=5)
            parent.reorder_child(i, len(parent) - 2)

    def remove_elements(self):
        [x.parent.remove(x) for x in self.__containers + [self.__desc_label] if x != None and x.parent != None]
        [x.set_text("") for x in self.__parameters.values()]

    def open_state(self, node):
        for tag, entry in self.__parameters.items():
            n = node.find("./parameters/%s" % (tag,))
            if n != None:
                entry.set_text(n.text)

    def xml(self, name):
        node = et.Element("distribution")

        nname = et.Element("name")
        nname.text = name

        base = et.Element("base")
        base.text = self.__name

        node.append(nname)
        node.append(base)

        parameters = et.Element("parameters")

        for tag, entry in self.__parameters.items():
            n = et.Element(tag)
            n.text = entry.get_text().strip()

            parameters.append(n)

        node.append(parameters)
        return node

    @property
    def name(self):
        return self.__name

    @property
    def pretty_name(self):
        return self.__pretty_name
